package com.hyd.hx_adr.exception;

import com.hyd.hx_adr.domain.entity.JsonResult;
import com.hyd.hx_adr.utils.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;
import com.hyd.hx_adr.domain.enums.ResCode;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@ControllerAdvice
@Slf4j
public class ExceptionHandle {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public JsonResult<String> baseErrorController(HttpServletRequest request, HttpServletResponse response, Exception e) {
        e.printStackTrace();
        response.setStatus(200);

        log.info("URI==>{}", request.getRequestURI());

        if (e instanceof NoHandlerFoundException) {

            return ResultUtils.error("请求的资源不存在");
        }

        /**
         * 参数异常
         */
        if(e instanceof MethodArgumentNotValidException){
            MethodArgumentNotValidException exp = (MethodArgumentNotValidException) e;
            BindingResult bindResult =  exp.getBindingResult();
            log.error(exp.getMessage());
            return ResultUtils.error(bindResult.getFieldError().getDefaultMessage());
        }

        if (e instanceof BusinessException) {
            log.error(e.getMessage());
            return ResultUtils.error(e.getMessage());
        }

        /**
         * 权限校验异常
         */
        if(e instanceof AuthenticationException) {
            log.error(e.getMessage());
            return ResultUtils.response(ResCode.AUTHENTICATION, e.getMessage(), false);
        }

        return ResultUtils.error(e.getMessage() != null ? e.getMessage() : "系统错误，请稍后再试");
    }

}
